import { login, getUser, getCheckList, alterTodo, alterCheckTitle } from '@/server/axios'
// 代办清单模块
export default {
  state: {
    // 待办事项列表
    checkList: [],
    // 待办事项对象
    checkId: ''
  },
  mutations: {
    getCheckList (state, data) {
      const checkList = data.data
      state.checkList = checkList
    },
    getCheckid (state, data) {
      const { id } = data
      state.checkId = id
    }
  },
  actions: {
    // 获得用户信息
    getUser ({ dispatch, commit, state, rootState }, date) {
      getUser().then((res) => {
        if (res.status === 200) {
          commit({
            type: 'loginSuccess',
            data: res.data
          })
          dispatch('getCheckList')
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    // 获取用户代办清单列表
    getCheckList ({ commit, state, rootState }, data) {
      const uid = rootState.user.id
      getCheckList(uid).then((res) => {
        if (res.status === 200) {
          commit({
            type: 'getCheckList',
            data: res.data
          })
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    // 修改代办事项
    alterTodo ({commit, state}, data) {
      const listId = state.checkId
      const index = data.index
      const isDone = data.isDone
      const params = {
        listId, index, isDone
      }
      return new Promise((resolve, reject) => {
        alterTodo(params).then((res) => {
          if (res.status === 200) {
            resolve()
          }
        }).catch((error) => {
          console.log(error)
          reject()
        })
      })
    },
    // 修改代办清单名称
    alterCheckTitle ({commit, state}, data) {
      const id = state.checkId
      const title = data.title
      let icon = data.icon
      if (!icon) {
        icon = 'list'
      }
      const params = {
        id, title, icon
      }
      return new Promise((resolve, reject) => {
        alterCheckTitle(params).then((res) => {
          if (res.status === 200) {
            resolve()
          }
        }).catch((error) => {
          console.log(error)
          reject()
        })
      })
    }
  },
  getters: {
    // 得到单一个代办清单内容
    check: state => {
      const list = state.checkList
      const id = state.checkId
      return list.filter((u) => u.id === id)[0] || {}
    }
  }
}
